package com.eightbears.beboy.ui.user.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShoppingAddressAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.cache.MyAddressCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.ShoppingAddressEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.greendao.District;
import com.eightbears.greendao.MyAddress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_DELETEALLADDRESS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_GETALLADDRESS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_SETADDRESS_DEFAULT;
import static com.eightbears.beboy.ui.user.activity.AddShoppingAddressActivity.EVENT_ADDRESS_SUCCESS;

/**
 * 收货地址
 */
public class ShoppingAddressActivity extends BaseActivity {

    public static final String PARAMS_ADDRESS_INFO = "addressInfo";

    @BindView(R.id.view_empty)
    View view_empty;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;

    private ShoppingAddressEntity.ShoppingAddress mShoppingAddress;
    private ShoppingAddressAdapter mShoppingAddressAdapter;
    private MyAddress myAddress;
    private DefaultDialog.Builder mBuilder;
    private int mPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_address);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        initAdapter();
        tv_title.setText(R.string.text_my_shopping_address);
    }

    @Override
    protected void initData() {
        myAddress = MyAddressCache.getInstance(this).getData();
        getUserAddressData();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        mShoppingAddressAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mPosition = position;
                mShoppingAddress = (ShoppingAddressEntity.ShoppingAddress) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.tv_getaddress_bianji:
                        startLocalActivity(ShoppingAddressActivity.this, AddShoppingAddressActivity.class,
                                PARAMS_ADDRESS_INFO, mShoppingAddress);
                        break;
                    case R.id.tv_getaddress_detele:
                        deleteAddress();
                        break;
                    case R.id.ll_moren:
                        putDefaultAddress();
                        break;
                }
            }
        });
    }

    private void deleteAddress() {
        if (mBuilder == null) {
            mBuilder = new DefaultDialog.Builder(ShoppingAddressActivity.this);
            mBuilder.setTitle(getString(R.string.alert_text));
            mBuilder.setMessage(getString(R.string.alert_delete_shopping_address));
            mBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getDeleteUserAddressData();
                    dialog.dismiss();
                }
            });
            mBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
        mBuilder.create().show();
    }

    @OnClick(R.id.btn_add_address)
    void addAddress() {
        startLocalActivity(this, AddShoppingAddressActivity.class);
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    private void initAdapter() {
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        mShoppingAddressAdapter = new ShoppingAddressAdapter();
        mShoppingAddressAdapter.openLoadAnimation();
        rv_list.setAdapter(mShoppingAddressAdapter);
    }

    /**
     * 获取用户收货地址数据
     */
    public void getUserAddressData() {
        OkHttpUtils.get().url(URL_RESET_GETALLADDRESS)
                .addHeader(CommonAPI.KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShoppingAddressEntity shoppingAddressEntity = GsonUtil.fromJson(response, ShoppingAddressEntity.class);
                if (shoppingAddressEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    if (shoppingAddressEntity.getData().size() > 0) {
                        view_empty.setVisibility(View.GONE);
                        mShoppingAddressAdapter.setNewData(shoppingAddressEntity.getData());
                    } else {
                        MyAddressCache.getInstance(ShoppingAddressActivity.this).clearAllData();
                        view_empty.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShoppingAddressActivity.this, status_error);
            }
        });
    }

    public void getDeleteUserAddressData() {
        OkHttpUtils.delete().url(URL_RESET_DELETEALLADDRESS + mShoppingAddress.getId())
                .addHeader(CommonAPI.KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                try {
                    if (response.contains("200")) {
                        if (myAddress.getMyAddressId().equals(mShoppingAddress.getId())) {
                            MyAddressCache.getInstance(ShoppingAddressActivity.this).clearAllData();
                        }
                        ShowToast.showShortToast(getString(R.string.alert_delete_success));
                        mShoppingAddressAdapter.remove(mPosition);
                        mShoppingAddressAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShoppingAddressActivity.this, status_error);
            }
        });
    }

    /**
     * 默认地址
     */
    public void putDefaultAddress() {
        OkHttpUtils.put().url(URL_RESET_SETADDRESS_DEFAULT + mShoppingAddress.getId())
                .addHeader(CommonAPI.KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                if (response.contains("200")) {
                    saveAddress();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShoppingAddressActivity.this, status_error);
            }
        });
    }

    private void saveAddress() {
        District province = DistrictCache.getInstance(mContext).getCacheById(mShoppingAddress.getProvince_id());
        District city = DistrictCache.getInstance(mContext).getCacheById(mShoppingAddress.getCity_id());
        District district = DistrictCache.getInstance(mContext).getCacheById(mShoppingAddress.getDistrict_id());
        String fullAddress = province.getName() + city.getName() + district.getName() + mShoppingAddress.getAddress();
        MyAddressCache.getInstance(ShoppingAddressActivity.this).clearAllData();
        myAddress = new MyAddress();
        myAddress.setAddress(fullAddress);
        myAddress.setMyAddressId(mShoppingAddress.getId());
        myAddress.setName(mShoppingAddress.getName());
        myAddress.setPhone(mShoppingAddress.getMobile());
        MyAddressCache.getInstance(ShoppingAddressActivity.this).saveData(myAddress);
        mShoppingAddressAdapter.notifyDataSetChanged();
        EventBus.getDefault().post(EVENT_ADDRESS_SUCCESS);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_ADDRESS_SUCCESS:
                mShoppingAddressAdapter.getData().clear();
                initData();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
